package org.ThreadDemo.sync;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Share3 {
    private int number =0 ;

    private Lock lock = new ReentrantLock();

    private Condition condition  = lock.newCondition();

    public void incr() throws InterruptedException {
        try {
            lock.lock();
            while(number != 0) {
                condition.await();
            }
            number ++ ;
            System.out.println(Thread.currentThread().getName()+"::"+number);
            condition.signalAll();
        }finally{
            lock.unlock();
        }
    }


    public void decr() throws InterruptedException {
        try {
            lock.lock();
            while(number != 1) {
                condition.await();
            }
            number-- ;
            System.out.println(Thread.currentThread().getName()+"::"+number);
            condition.signalAll();
        }finally{
            lock.unlock();
        }
    }

}
public class ThreadDemo03 {

    public static void main(String[] args) {
        Share3 share3 = new Share3();

        new Thread( ()-> {
            for(int i = 1;i<=100;i++){
                try{
                    share3.incr();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread( ()-> {
            for(int i = 1;i<=100;i++){
                try{
                    share3.decr();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();


        new Thread( ()-> {
            for(int i = 1;i<=100;i++){
                try{
                    share3.incr();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread( ()-> {
            for(int i = 1;i<=100;i++){
                try{
                    share3.decr();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();

    }




}
